package April._25.homework.work5;

import untils.TestFlag;

import java.io.*;
import java.net.Socket;
import java.util.Properties;
import java.util.Scanner;

public class RobatTask implements Runnable {
    Socket socket;

    public RobatTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        boolean flag = true;
//        //文件输入流
//        InputStream inputStream = null;
        while (flag) {
            String msg = null;
            try {
                //从socket获取消息
                //获取输入流socket
                if (TestFlag.testFlag) {
                    System.out.println("开始获取消息");
                }
                InputStream inputStream = socket.getInputStream();
                if (TestFlag.testFlag) {
                    System.out.println("11111");
                }
                //转换为字符流
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
//                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                //读取消息
                char[] chars = new char[1024];
                int read = inputStreamReader.read(chars);
                if (TestFlag.testFlag) {
                    System.out.println("read = " + read);
                }

                msg = new String(chars, 0, read);
                if (TestFlag.testFlag) {
                    System.out.println("msg = " + msg);
                }

                //从配置文件获取回答
                Properties properties = new Properties();
                properties.load(new InputStreamReader(new FileInputStream("fileTest\\config.properties"), "UTF-8"));
                String recive = properties.getProperty(msg);
                if (TestFlag.testFlag) {
                    System.out.println("recive = " + recive);
                }

                //发送答案
                //获取输出流socket
                OutputStream outputStream = socket.getOutputStream();
                //装换为字符流
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
                outputStreamWriter.write(recive);
                outputStreamWriter.flush();
                if (TestFlag.testFlag) {
                    System.out.println("回答发送完成");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

}
